package com.h117121.fashionshop.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.h117121.fashionshop.core.dom.SettingForm;

public class SettingValidator implements Validator {

	@SuppressWarnings("rawtypes")
	@Override
	public boolean supports(Class clazz) {
		return SettingForm.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "numItemPerPage",
				"required.numItemPerPage");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,
				"numMaxItemLeftPanel", "required.numMaxItemLeftPanel");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "numSimilarItem",
				"required.numSimilarItem");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "numMostSoldItem",
				"required.numMostSoldItem");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "numNewestItem",
				"required.numNewestItem");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,
				"numItemPerPageAdmin", "required.numItemPerPageAdmin");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,
				"numNewestItemAdmin", "required.numNewestItemAdmin");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,
				"numMostSoldItemAdmin", "required.numMostSoldItemAdmin");
		if (!errors.hasErrors()) {
			SettingForm setting = (SettingForm) target;
			if (setting.getNumItemPerPage() <= 0) {
				errors.rejectValue("numItemPerPage", "invalid.numItemPerPage");
			}

			if (setting.getNumItemPerPageAdmin() <= 0) {
				errors.rejectValue("numItemPerPageAdmin",
						"invalid.numItemPerPageAdmin");
			}

			if (setting.getNumMaxItemLeftPanel() <= 0) {
				errors.rejectValue("numMaxItemLeftPanel",
						"invalid.numMaxItemLeftPanel");
			}

			if (setting.getNumSimilarItem() <= 0) {
				errors.rejectValue("numSimilarItem", "invalid.numSimilarItem");
			}

			if (setting.getNumMostSoldItem() <= 0) {
				errors.rejectValue("numMostSoldItem", "invalid.numMostSoldItem");
			}

			if (setting.getNumNewestItem() <= 0) {
				errors.rejectValue("numNewestItem", "invalid.numNewestItem");
			}
			
			if (setting.getNumNewestItemAdmin() <= 0) {
				errors.rejectValue("numNewestItemAdmin", "invalid.numNewestItemAdmin");
			}

			if (setting.getNumMostSoldItemAdmin() <= 0) {
				errors.rejectValue("numMostSoldItemAdmin", "invalid.numMostSoldItemAdmin");
			}
		}
	}

}
